package com.neptune.imapp.ui.compose.screen.frontPage.register

import android.annotation.SuppressLint
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CutCornerShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.PagerState
import com.google.accompanist.pager.rememberPagerState
import com.neptune.imapp.R
import com.neptune.imapp.ui.compose.screen.frontPage.FrontPageViewModel
import com.neptune.imapp.ui.compose.screen.frontPage.login.InputTextField
import com.neptune.imapp.ui.compose.screen.frontPage.login.autoCloseKeyboard
import com.neptune.imapp.utils.RegexUtil

@OptIn(ExperimentalComposeUiApi::class, ExperimentalPagerApi::class)
@Composable
fun Register(viewModel: FrontPageViewModel, navController: NavController) {
    val keyboardController = LocalSoftwareKeyboardController.current
    val focusManager = LocalFocusManager.current
    Column(
        modifier = Modifier
            .autoCloseKeyboard(keyboardController, focusManager)
            .fillMaxHeight()
            .padding(start = 20.dp, end = 20.dp),
    ) {
        Text(
            text = "Register",
            fontSize = 30.sp,
            fontFamily = FontFamily.Cursive,
            textAlign = TextAlign.Center,
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 50.dp),
            letterSpacing = 8.sp
        )
        val pagerState = rememberPagerState()
        HorizontalPager(count = 7, userScrollEnabled = false, state = pagerState) {
            Column(
                verticalArrangement = Arrangement.spacedBy(20.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier.fillMaxWidth()
            ) {
                when (it) {
                    0 -> Page1(viewModel = viewModel, pagerState = pagerState)
                    1 -> Page2(viewModel = viewModel, navController = navController)
                }
            }
        }
    }
}

@OptIn(ExperimentalPagerApi::class)
@Composable
fun Page1(viewModel: FrontPageViewModel, pagerState: PagerState) {
    val captcha = remember {
        mutableStateOf(false)
    }
    AnimatedVisibility(visible = viewModel.telephoneCheck.value) {
        Snackbar {
            Text(text = "手机号已被注册,请更换手机号")
        }
    }
    InputTextField(
        bindValue = viewModel.baseInfo.telephone,
        label = "PhoneNumber",
        placeholder = "Please Input your Phone",
        trailingIcon = {
            IconButton(
                content = {
                    Icon(
                        painter = painterResource(R.drawable.ic_delete),
                        contentDescription = null
                    )
                },
                enabled = viewModel.baseInfo.telephone.value.isNotEmpty(),
                onClick = {
                    viewModel.clearString(viewModel.baseInfo.telephone)
                }
            )
        },
        modifier = Modifier
            .onFocusChanged {
                viewModel.isPhoneError.value =
                    RegexUtil.checkPhoneNumber(viewModel.baseInfo.telephone)
            }
            .fillMaxWidth()
            .wrapContentHeight(),
        isError = viewModel.isPhoneError.value,
        imeAction = ImeAction.Next
    )
    val time = remember {
        mutableStateOf("Get")
    }
    InputTextField(
        bindValue = viewModel.captcha,
        label = "Captcha",
        placeholder = "Input Captcha",
        modifier = Modifier
            .fillMaxWidth(),
        trailingIcon = {
            Button(
                content = {
                    Text(text = time.value)
                },
                enabled = viewModel.baseInfo.telephone.value.isNotEmpty(),
                onClick = {
                    viewModel.checkTelephone(time)
                },
                shape = CutCornerShape(30),
            )
        },
        imeAction = ImeAction.Done
    )

    AnimatedVisibility(visible = captcha.value) {
        InputTextField(
            bindValue = viewModel.baseInfo.password,
            label = "Password",
            placeholder = "Please Input your Password",
            leadingIcon = {
                IconButton(
                    content = {
                        Icon(
                            painter = painterResource(if (viewModel.passwordVisibility.value) R.drawable.ic_invisible else R.drawable.ic_visible),
                            contentDescription = null
                        )
                    },
                    onClick = {
                        viewModel.passwordInputClick()
                    }
                )
            },
            trailingIcon = {
                IconButton(
                    content = {
                        Icon(
                            painter = painterResource(R.drawable.ic_delete),
                            contentDescription = null
                        )
                    },
                    enabled = viewModel.baseInfo.password.value.isNotEmpty(),
                    onClick = {
                        viewModel.clearString(viewModel.passwordVal)
                    }
                )
            },
            modifier = Modifier
                .fillMaxWidth(),
            visualTransformation = if (viewModel.passwordVisibility.value) PasswordVisualTransformation() else VisualTransformation.None,
            imeAction = ImeAction.Done
        )
    }
    Button(
        onClick = {
            if (!captcha.value) {
                if (viewModel.captcha.value == "1234") {
                    captcha.value = true
                }
            } else {
                viewModel.register(pagerState)
            }
        },
        shape = RoundedCornerShape(5.dp)
    ) {
        Text("下一步")
    }
}

@Composable
fun Page2(viewModel: FrontPageViewModel, navController: NavController) {
    Image(
        painter = painterResource(id = if (viewModel.baseInfo.sex.value == 1) R.drawable.ic_boy else R.drawable.ic_girl),
        contentDescription = null,
        modifier = Modifier
            .size(100.dp),
        alignment = Alignment.Center
    )
    BasicTextField(
        value = viewModel.baseInfo.username.value,
        onValueChange = { viewModel.baseInfo.username.value = it },
        singleLine = true,
        modifier = Modifier.fillMaxWidth(),
        textStyle = TextStyle(textAlign = TextAlign.Center, fontSize = 20.sp),
        decorationBox = @Composable { innerTextField ->
            if (viewModel.baseInfo.username.value.isEmpty())
                Text(
                    text = "请输入真实姓名",
                    modifier = Modifier.fillMaxWidth(),
                    textAlign = TextAlign.Center,
                    fontSize = 20.sp,
                    color = Color.Gray
                )
            innerTextField()
        })
    Sex(sex = viewModel.baseInfo.sex)
    Email(email = viewModel.baseInfo.email)
    Birth(birth = viewModel.baseInfo.birthDay)
    Button(onClick = {
        viewModel.postBasicInfo(navController = navController)
    }, shape = RoundedCornerShape(10.dp)) {
        Text(text = "下一步")
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Sex(sex: MutableState<Int>) {
    Row(horizontalArrangement = Arrangement.Center) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            Text(text = "男", fontSize = 20.sp)
            RadioButton(selected = sex.value == 1, onClick = { sex.value = 1 })
        }
        Row(verticalAlignment = Alignment.CenterVertically) {
            RadioButton(selected = sex.value == 0, onClick = { sex.value = 0 })
            Text(text = "女", fontSize = 20.sp)
        }
    }
}

@SuppressLint("RememberReturnType")
@Composable
fun Email(email: MutableState<String>) {
    val expanded = remember {
        mutableStateOf(false)
    }
    val list = listOf("@QQ.com", "@163.com", "@GMail.com", "@Mail.com")
    val emailPostFix = remember {
        mutableStateOf(list[0])
    }
    val emailPre = remember {
        mutableStateOf("")
    }
    Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
        TextField(
            value = emailPre.value,
            onValueChange = {
                emailPre.value = it
                email.value = it + emailPostFix.value
            },
            placeholder = { Text(text = "请输入您的邮箱") },
            modifier = Modifier.weight(0.6f)
        )
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = Modifier.weight(0.4f)
        ) {
            TextField(
                value = emailPostFix.value,
                onValueChange = {},
                enabled = false,
                modifier = Modifier
                    .clickable {
                        expanded.value = true
                    },
                textStyle = TextStyle(textAlign = TextAlign.Center)
            )
            DropdownMenu(
                expanded = expanded.value,
                onDismissRequest = { }
            ) {
                list.forEach {
                    DropdownMenuItem(text = { Text(text = it) }, onClick = {
                        emailPostFix.value = it
                        expanded.value = false
                    })
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Birth(birth: MutableState<String>) {
    val yearSelect = remember {
        mutableStateOf(false)
    }
    val monthSelect = remember {
        mutableStateOf(false)
    }
    var year = "年"
    var month = "月"
    Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
        Card(
            modifier = Modifier
                .weight(0.5f)
        ) {
            Text(
                text = "出生",
                fontSize = 20.sp,
                modifier = Modifier
                    .padding(15.dp)
                    .fillMaxWidth(),
                textAlign = TextAlign.Center
            )
        }
        Card(
            modifier = Modifier
                .weight(0.5f)
        ) {
            Row(horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth()) {
                Text(text = year, fontSize = 20.sp, modifier = Modifier
                    .padding(15.dp)
                    .clickable(
                        interactionSource = MutableInteractionSource(),
                        indication = null
                    ) {
                        yearSelect.value = true
                    })
            }
            DropdownMenu(
                expanded = yearSelect.value,
                onDismissRequest = { /*TODO*/ },
                modifier = Modifier.height(200.dp)
            ) {
                for (i in 1970..2006) {
                    DropdownMenuItem(text = { Text(text = i.toString()) }, onClick = {
                        year = i.toString()
                        birth.value = "$year-$month"
                        yearSelect.value = false
                    })
                }
            }
        }
        Card(
            modifier = Modifier
                .weight(0.5f)
        ) {
            Row(horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth()) {
                Text(text = month, fontSize = 20.sp, modifier = Modifier
                    .padding(15.dp)
                    .clickable(
                        interactionSource = MutableInteractionSource(),
                        indication = null
                    ) {
                        monthSelect.value = true
                    })
            }
            DropdownMenu(
                expanded = monthSelect.value,
                onDismissRequest = { /*TODO*/ },
                modifier = Modifier.height(200.dp)
            ) {
                for (i in 1..12) {
                    DropdownMenuItem(text = { Text(text = i.toString()) }, onClick = {
                        month = i.toString()
                        birth.value = "$year-$month"
                        monthSelect.value = false
                    })
                }
            }
        }
    }
}
